

#include "session.h"
#include "stun_message.h"
#include "turn_server.h"

Session::Session(TurnServer * turn_server)
{
    m_turn_server = turn_server;
    // 60 second expire
    m_latest_update_time = time(nullptr);
    m_data_buffer        = new DataBuffer(m_turn_server->m_udp_server->GetSocketFd());
}

Session::~Session()
{
    delete m_data_buffer;
    m_data_buffer = nullptr;
}

void Session::ParserData(UdpBufferPacket *packet)
{
    m_latest_update_time = time(nullptr);
    do
    {
        std::unique_lock<std::mutex> lk(m_mutx);

        StunMessage message;
        int use_length = 0;
        auto status = message.ParseStunMessage(packet, use_length);

        bool is_break = false;
        switch(status)
        {
            case EmParseFailStatus:
            {
                is_break = true;
                // drop all data
                m_data_buffer->RemoveData(use_length);
                printf("drop all packet data.\n");
                break;    
            }
            case EmDataNotEnoughStatus:
            {
                is_break = true;
                // need more data
                break;
            }
            case EmParseFinishStatus:
            {
                is_break = false;
                // process message 20 is stun header length
                m_data_buffer->RemoveData(20 + message.GetAttrLength());
                
                lk.unlock();
                m_turn_server->ProcessStunMessage(*packet, message);
                break;
            }
            default:
            {
                is_break = true;
                break;
            }
        }
        if (is_break)
        {
            break;
        }

    }while(true);
}